package com.lg.wxq.ui;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.lg.wxq.bean.Task;
import com.lg.wxq.config.Strings;
import com.lg.wxq.config.TaskType;
import com.lg.wxq.utils.DebugUtils;
import com.lg.wxq.utils.FontsUtils;
import com.lg.wxq.utils.StringUtils;

public class NewWeiboActivity extends BaseActivity {

	private TextView textCountTv;
	private EditText weiboEt;
	private ArrayList<String> weiboTextArray = new ArrayList<String>();
	private boolean textChanged = true;

	private ImageGetter imageGetter = new ImageGetter() {

		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newweibo);

		textCountTv = (TextView) findViewById(R.id.newweibo_tv_textcount);
		weiboEt = (EditText) findViewById(R.id.newweibo_et_weibo);
		weiboEt.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				DebugUtils.debug("on " + s.toString() + " start:" + start + " before:" + before + " count:" + count + " arrayCount:" + weiboTextArray.size());
				if (textChanged) {
					String string = s.toString();
					if (before != 0) {
						for (int i = before + start - 1; i >= start; i--) {
							DebugUtils.debug("i" + i);
							weiboTextArray.remove(i);
						}
					}
					for (int i = start; i < start + count; i++) {
						String sub = string.substring(i, i + 1);
						weiboTextArray.add(i, sub);
					}

					weiboTextArray = StringUtils.getNewArray(weiboTextArray, start + count - 1);
					String newStr = StringUtils.stringArrayToHtml(weiboTextArray);
					textChanged = false;
					weiboEt.setText(Html.fromHtml(newStr, imageGetter, null));
					if (StringUtils.index != -1) {
						weiboEt.setSelection(StringUtils.index);
						StringUtils.index = -1;
					}
				} else {
					textChanged = true;
				}

			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		
		weiboEt.setOnEditorActionListener(new OnEditorActionListener() {
			
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				
				return false;
			}
		});
		
		Typeface typeFace = FontsUtils.getTypeFace(this, "gp1.ttf");
		textCountTv.setTypeface(typeFace);
	}

	@Override
	public void clickButton(View v) {
		super.clickButton(v);
		switch (v.getId()) {
		case R.id.newweibo_bt_return:
			finish();
			break;
		case R.id.newweibo_bt_send:
			String status = StringUtils.stringArrayToString(weiboTextArray);
			update(status);
			break;
		case R.id.newweibo_ib_face:
			// String string = weiboEt.getText().toString();
			// weiboEt.setText(Html.fromHtml(string + "<img src='" +
			// R.drawable.face001 + "'/>", imageGetter, null));
			int selectionStart = weiboEt.getSelectionStart();
			weiboTextArray.add(selectionStart, "[微笑]");
			textChanged = false;
			String newStr = StringUtils.stringArrayToHtml(weiboTextArray);
			weiboEt.setText(Html.fromHtml(newStr, imageGetter, null));
			weiboEt.setSelection(selectionStart + 1);
			break;
		}
	}

	/**
	 * 发表微博
	 * 
	 * @param status
	 *            要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
	 */
	private void update(String status) {
		update(status, 0.0f, 0.0f, "");
	}

	/**
	 * 发表微博
	 * 
	 * @param status
	 *            要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
	 * @param latF
	 *            纬度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0。
	 * @param longF
	 *            经度，有效范围：-180.0到+180.0，+表示东经，默认为0.0。
	 * @param annotations
	 *            元数据，主要是为了方便第三方应用记录一些适合于自己使用的信息，每条微博可以包含一个或者多个元数据，
	 *            必须以json字串的形式提交，字串长度不超过512个字符，具体内容可以自定。
	 */
	private void update(String status, float latF, float longF, String annotations) {
		Task task = getTask(actID, TaskType.TS_STATUSES_UPDATE, false);
		task.addParam(Strings.ACCESS_TOKEN, weibo.getAccessToken().getToken());
		task.addParam(Strings.STATUS, status);
		task.addParam(Strings.LAT, latF);
		task.addParam(Strings.LONG, longF);
		task.addParam(Strings.ANNOTATIONS, "[{\"haixiao\":\"haixiao\",\"gp\":\"gp\"},{\"haixiao\":\"haixiao\"}]");
		taskManager.addTask(task);
	}

	@Override
	public void refresh(Task task) {
		super.refresh(task);
		switch (task.getTaskType()) {
		case TaskType.TS_STATUSES_UPDATE:
			Toast.makeText(this, Strings.SEND_WEIBO_SUCCESS, 1000).show();
			finish();
			break;

		}
	}

}
